package com.linciping.room.db

import androidx.room.RoomDatabase
import java.lang.reflect.Method

object DBManager {

    private var roomDatabase: RoomDatabase? = null
    private lateinit var daoMap: HashMap<String, Method>

    fun init(roomDatabase: RoomDatabase) {
        this.roomDatabase = roomDatabase
        val daoMethods = roomDatabase::class.java.methods
        daoMap = HashMap(daoMethods.size)
        for (daoMethod in daoMethods) {
            daoMap[daoMethod.returnType.name] = daoMethod
        }
    }

    fun <T> getDao(daoClass: Class<T>): T? {
        if (roomDatabase == null) return null
        try {
            val className = daoClass.name
            if (daoMap.containsKey(className)) {
                val daoMethod = daoMap[className]!!
                return daoMethod.invoke(roomDatabase) as T?
            }
            return null
        } catch (ex: Exception) {
            return null
        }
    }
}